//! 任务调度器模块
//! 
//! 提供任务调度和管理的功能

use crate::utils::error::{YayaError, Result};

/// 任务状态
#[derive(Debug, Clone, PartialEq)]
pub enum TaskState {
    Ready,      // 就绪
    Running,    // 运行中
    Blocked,    // 阻塞
    Terminated, // 终止
}

/// 任务优先级
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum TaskPriority {
    Low = 0,
    Normal = 1,
    High = 2,
    RealTime = 3,
}

/// 任务控制块（TCB）
pub struct TaskControlBlock {
    pub id: u32,
    pub state: TaskState,
    pub priority: TaskPriority,
    pub stack_pointer: usize,
    pub program_counter: usize,
    pub stack_size: usize,
}

/// 调度器
pub struct Scheduler {
    tasks: Vec<TaskControlBlock>,
    current_task: Option<u32>,
    task_counter: u32,
}

impl Scheduler {
    /// 创建新的调度器
    pub fn new() -> Result<Self, YayaError> {
        Ok(Scheduler {
            tasks: Vec::new(),
            current_task: None,
            task_counter: 0,
        })
    }
    
    /// 初始化调度器
    pub fn init() -> Result<(), YayaError> {
        info!("初始化任务调度器");
        Ok(())
    }
    
    /// 关闭调度器
    pub fn shutdown() -> Result<(), YayaError> {
        info!("关闭任务调度器");
        Ok(())
    }
    
    /// 创建新任务
    pub fn create_task(&mut self, entry_point: usize, stack_size: usize, priority: TaskPriority) -> Result<u32, YayaError> {
        let task_id = self.task_counter;
        self.task_counter += 1;
        
        let task = TaskControlBlock {
            id: task_id,
            state: TaskState::Ready,
            priority,
            stack_pointer: 0,
            program_counter: entry_point,
            stack_size,
        };
        
        self.tasks.push(task);
        info!("创建任务: ID={}, 优先级={:?}", task_id, priority);
        
        Ok(task_id)
    }
    
    /// 调度下一个任务
    pub fn schedule(&mut self) -> Option<u32> {
        if self.tasks.is_empty() {
            return None;
        }
        
        // 简单的轮转调度算法
        let next_task = if let Some(current) = self.current_task {
            let current_index = self.tasks.iter().position(|t| t.id == current).unwrap_or(0);
            (current_index + 1) % self.tasks.len()
        } else {
            0
        };
        
        if let Some(task) = self.tasks.get(next_task) {
            if task.state == TaskState::Ready {
                self.current_task = Some(task.id);
                Some(task.id)
            } else {
                None
            }
        } else {
            None
        }
    }
    
    /// 获取当前运行的任务
    pub fn current_task(&self) -> Option<&TaskControlBlock> {
        self.current_task.and_then(|id| self.tasks.iter().find(|t| t.id == id))
    }
    
    /// 阻塞指定任务
    pub fn block_task(&mut self, task_id: u32) -> Result<(), YayaError> {
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == task_id) {
            task.state = TaskState::Blocked;
            Ok(())
        } else {
            Err(YayaError::InvalidParameter("任务不存在".into()))
        }
    }
    
    /// 唤醒指定任务
    pub fn wake_task(&mut self, task_id: u32) -> Result<(), YayaError> {
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == task_id) {
            task.state = TaskState::Ready;
            Ok(())
        } else {
            Err(YayaError::InvalidParameter("任务不存在".into()))
        }
    }
}

/// 获取全局调度器实例
pub fn get_scheduler() -> &'static mut Scheduler {
    static mut SCHEDULER: Option<Scheduler> = None;
    
    unsafe {
        if SCHEDULER.is_none() {
            SCHEDULER = Some(Scheduler::new().unwrap());
        }
        SCHEDULER.as_mut().unwrap()
    }
}